package wta.mongo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

/**
 * 第一批数据的 02 健康问卷
 * 更新用户的体检问答题信息
 * @author icyfox
 *
 */
public class UpdateUserQuestion {

	private static Mongo mongo;
	private static DB db;
	private static DBCollection coll;

	public static void main(String[] args) throws Exception {
		
		mongo = new Mongo("10.110.150.69");
		
		db = mongo.getDB("china");
		//coll = db.getCollection("users");
		coll = db.getCollection("positive");
		
		//File dic  = new File("D:\\Now\\ciming\\慈铭数据.20150428\\02");
		File dic  = new File("D:\\百度云同步盘\\Now\\ciming\\数据\\4ciming11w");
		String[] list = dic.list(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.contains("健康问卷信息");
			}
		});
		
		for (String string : list) {
			System.out.println(string);
			insert(dic.getAbsolutePath() +'\\'+ string);
		}
		
		mongo.close();
	}

	private static void insert(String file) throws Exception {
		System.out.println("开始插入文件："+file);
		BufferedReader br = new BufferedReader(new FileReader(file)); //UTF-8打开文件
		String curID = null;
		BasicDBObject toModify = null;
		
		while (true) {
			String line = br.readLine(); //读入一行数据
			if (line == null) { //如果是空行，说明文件结束
				BasicDBObject toFind = new BasicDBObject(); //一个查询对象
				toFind.put("uid", curID); //加入需要查询的数据
				DBObject obj = coll.findOne(toFind); //查找一个结果
				if (obj == null) //如果找到了那个对象
					System.err.println(curID + " not found");
				else{
					WriteResult re = coll.update(obj, new BasicDBObject("$set", toModify), true, false);//追加字段
					//System.out.println(curID);
				}
				break;
			}
			if (line.contains("以上疾病治疗情况及现状")) continue; //去掉这种行
			System.out.println(line);
			String[] info = line.split("\\|");
			
			System.out.println(info[0]);
			
			if (curID == null){//如果是第一行
				curID = info[0]; //当前ID
				toModify = new BasicDBObject(); //要修改的对象
				toModify.put(info[1], info[2]); //增加一个字段
			}else if (!curID.equals(info[0])) { //如果是一个新的ID
				//把老数据添加进去
				BasicDBObject toFind = new BasicDBObject();
				toFind.put("uid", curID);
				
				DBObject obj = coll.findOne(toFind); //找到那一行
				if (obj == null)
					System.err.println(info[0] + " not found");
				else{
					WriteResult re = coll.update(obj, new BasicDBObject("$set", toModify), true, false);
					//System.out.println(curID);
				}
				
				toModify = new BasicDBObject(); //新建下一个需要插入的对象
				toModify.put(info[1], info[2]);
				curID = info[0];
			}else {
				toModify.put(info[1], info[2]); //还是上一位用户。
			}
		}
		
		br.close();
	}
	
}
